package com.fengye.cluster.impl;

import com.fengye.cluster.ClusterStrategy;
import com.fengye.model.ProviderService;
import com.google.common.collect.Lists;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 软负载加权轮询算法
 * @Author fengye
 * @Date 2023/2/15 11:49
 **/
public class WeightPollingClusterStrategyImpl extends AbstractClusterStrategt {

    /** 计数器 */
    private AtomicInteger count = new AtomicInteger(0);
    /** 计数器锁 */
    private Lock lock = new ReentrantLock();

    @Override
    public ProviderService doSelect(List<ProviderService> providerServiceList) {
        ProviderService providerService = null;

        try {
            if(lock.tryLock() || lock.tryLock(10, TimeUnit.MICROSECONDS)) {
                // 存放加权后的服务提供者列表
                List<ProviderService> providerServices = Lists.newLinkedList();
                for (ProviderService provider : providerServiceList) {
                    int weight = provider.getWeight();
                    for (int i=0;i < weight;i++) {
                        providerServices.add(provider.clone());
                    }
                }
                if(count.intValue() >= providerServices.size()){
                    count.compareAndSet(count.intValue(), 0);
                }
                providerService = providerServices.get(count.intValue());
                count.getAndIncrement();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
        return providerService;
    }
}
